package utils

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import netv1 "k8s.io/api/networking/v1"

// ExternalIPsAnnotation is the annotation key for comma separated list of external IP addresses
const ExternalIPsAnnotation = "k8gb.io/exposed-ip-addresses"

// MergeAnnotations adds or updates annotations from source to target and returns merge
func MergeAnnotations(target map[string]string, source map[string]string, controlledAnnotations ...string) map[string]string {
	if target == nil {
		target = make(map[string]string)
	}
	if source == nil {
		source = make(map[string]string)
	}
	for _, key := range controlledAnnotations {
		if val, ok := source[key]; ok {
			if target[key] != val {
				target[key] = val
			}
		}
	}

	return target
}

func SetCommonGslbLabels(ingress *netv1.Ingress) {
	if ingress.Labels == nil {
		ingress.Labels = make(map[string]string)
	}
	ingress.Labels["app.k8gb.io/managed-by"] = "gslb"
}

// EqualPredefinedAnnotations checks if there has been a change in controlledAnnotations, it ignores the rest
func EqualPredefinedAnnotations(a1, a2 map[string]string, controlledAnnotations ...string) bool {
	a1K8gbValues := map[string]string{}
	a2K8gbValues := map[string]string{}
	for _, v := range controlledAnnotations {
		if val, ok := a1[v]; ok {
			a1K8gbValues[v] = val
		}
		if val, ok := a2[v]; ok {
			a2K8gbValues[v] = val
		}
	}
	return EqualAnnotations(a1K8gbValues, a2K8gbValues)
}

func EqualAnnotations(a, b map[string]string) bool {
	if len(a) != len(b) {
		return false
	}
	for k := range a {
		if b[k] != a[k] {
			return false
		}
	}
	return true
}
